<?php
/*
 * 话题
 */
class topicModel{
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }
    
    /*
     * 获得话题详情
     */
    public function getTopicInfo($topic){
        $redisKey = REDIS_PREFIX.'Topic'.md5($topic);
        $topicInfo = $this->redis->hgetall($redisKey);
        if(!isset($topicInfo['topic_id'])){
            $topicInfo = $this->db->getRowTable('r_topic',[],"name='$topic'");
            if(!$topicInfo){
                return false;
            }
            $this->redis->hmset($redisKey,$topicInfo);
            $this->redis->expire($redisKey,5184000);//90天过期
        }
        
        if(!isset($topicInfo['thumb_img']) || !$topicInfo['thumb_img']){
            $topicInfo['thumb_img'] = [];
        }elseif(common::is_json($topicInfo['thumb_img'])){
            $topicInfo['thumb_img'] = json_decode($topicInfo['thumb_img'],true);
        }
        
        $topicInfo['feature_posts'] = isset($topicInfo['feature_posts'])&&$topicInfo['feature_posts'] ? json_decode($topicInfo['feature_posts']) : [];
        
        return $topicInfo;
    }
    
    public function insert($data){
        if(!isset($data['uid']) || !$data['uid']){
            return false;
        }
        if(!isset($data['name']) || !$data['name']){
            return false;
        }
        if(!isset($data['status'])){
            $data['status'] = 0;
        }
        if(!isset($data['thumb_img'])){
            $data['thumb_img'] = '[]';
        }
        if(is_array($data['thumb_img'])){
            $data['thumb_img'] = json_encode($data['thumb_img']);
        }
        $data['addtime'] = time();
        $data['pv'] = 0;
        
        $topic_id = $this->db->insertRowTable('r_topic',$data);
        if(!$topic_id){
            return false;
        }
        
        return $topic_id;
    }
    
    public function update($data){
        $row = $this->db->getRowTable('r_topic',[],'topic_id='.$data['topic_id']);
        if(isset($data['thumb_img']) && is_array($data['thumb_img'])){
            $data['thumb_img'] = json_encode($data['thumb_img']);
        }
        if(isset($data['feature_posts']) && is_array($data['feature_posts'])){
            $data['feature_posts'] = json_encode($data['feature_posts']);
        }
        $res = $this->db->updateRowTable('r_topic',$data);
        if(!$res){
            return false;
        }
        
        $redisKey = REDIS_PREFIX.'Topic'.md5($row['name']);
        $this->redis->del($redisKey);
        
        if(isset($data['status']) && $data['status']==1 && $row['status']==0){
            $featuredTopic = $this->getFeaturedTopics();
            foreach($featuredTopic as $key=>$topic){
                if($topic['topic_id'] == $data['topic_id']){
                    array_splice($featuredTopic,$key,1);
                    $this->setFeaturedTopics($featuredTopic);
                    break;
                }
            }
        }
        
        return $res;
    }
    
    public function destroy($id){
        $data = $this->db->getRowTable('r_topic',[],'topic_id='.$id);
        $data['status'] = 1;
        return $this->update($data);
    }
    
    /*
     * 插入帖子图片
     */
    public function filterPost($postInfo){
        $first_img = null;
        if(isset($postInfo['thumb_img']) && common::is_json($postInfo['thumb_img'])){
            $thumb_img = json_decode($postInfo['thumb_img']);
            $first_img = current($thumb_img);
        }
        
        $string = strip_tags($postInfo['title'].$postInfo['content']);
        preg_match_all("/#[^@]+?#/",$string,$matches);
        if(empty($matches)){
            return;
        }
        
        $_matches = array_unique($matches[0]);
        $now = time();
        foreach($_matches as $match){
            $topicInfo = $this->getTopicInfo($match);
            if(!$topicInfo){
                $this->insert([
                    'uid' => $postInfo['uid'],
                    'name' => $match,
                    'thumb_img' => $first_img ? [$first_img] : [],
                    'last_time' => $now,
                    'post_count' => 1
                ]);
                $topicInfo = $this->getTopicInfo($match);
            }else{
                if($first_img){
                    array_unshift($topicInfo['thumb_img'],$first_img);
                    if(count($topicInfo['thumb_img']) > 3){
                        $topicInfo['thumb_img'] = array_slice($topicInfo['thumb_img'],0,3);
                    }
                    $topicInfo['last_time'] = $now;
                    $this->update($topicInfo);
                    $topicInfo = $this->getTopicInfo($match);
                }
                //添加统计
                $redisKey = REDIS_PREFIX.'Topic'.md5($match);
                $this->redis->hset($redisKey,'last_time',$now);
                $this->redis->hincrby($redisKey,'post_count',1);
                $topicInfo = $this->getTopicInfo($match);
                if($topicInfo['post_count']%50==0){
                    $this->update($topicInfo);
                    $topicInfo = $this->getTopicInfo($match);
                }
            }
            
            if($topicInfo){
                $this->db->insertRowTable('r_topic_relation',[
                    'topic_id' => $topicInfo['topic_id'],
                    'news_id' => $postInfo['news_id'],
                    'addtime' => $now
                ]);
            }
        }
        return;
    }
    
    /*
     * 获得推荐话题列表
     */
    public function getFeaturedTopics(){
        $topics = $this->redis->get(REDIS_PREFIX.'FeaturedTopic');
        $topics = $topics ? json_decode($topics,true) : [];
        foreach($topics as &$topic){
            $topic = array_merge($topic,$this->getTopicInfo($topic['name']));
        }
        return $topics;
    }
    
    public function setFeaturedTopics($data){
        $redisKey = REDIS_PREFIX.'FeaturedTopic';
        $data = json_encode($data);
        $this->redis->set($redisKey,$data);
    }
    
    /*
     * 增加pv
     */
    public function countStatistics($topic){
        $redisKey = REDIS_PREFIX.'Topic'.md5($topic);
        $topicInfo = $this->getTopicInfo($topic);
        $this->redis->hincrby($redisKey,'pv',1);
        $topicInfo = $this->getTopicInfo($topic);
        if($topicInfo['pv']%50==0){
            $this->update($topicInfo);
        }
    }

    /*
     * 获得话题对应帖子id
     */
    public function getPostIdFromTopic($topic_id,$news_id,$limit){
        if(empty($topic_id)){
            return [];
        }
        $sql = "select news_id from r_topic_relation where topic_id=$topic_id";
        if($news_id){
            $sql .= " AND news_id < $news_id ";
        }
        $rows = $this->db->getAll($sql." order by news_id desc limit $limit");
        $ids = [];
        foreach($rows as $row){
            $ids[] = $row['news_id'];
        }
        return $ids;
    }

    /**
     * 查询话题的全部帖子ID
     * @param $topicId 话题ID
     * @return array  [1,2,3,4……]
     */
    public function getAllPostIdFromTopic($topicId) {
        $sql = "select news_id from r_topic_relation where topic_id=$topicId";
        $rows = $this->db->getAll($sql);
        $ids = [];
        foreach($rows as $row){
            $ids[] = $row['news_id'];
        }
        return $ids;
    }

    /**
     * 查询话题的用户数
     * @param $topicName 话题名称
     * @return int
     */
    public function getTopicUsersNum($topicName) {
        $topicInfo = $this->getTopicInfo($topicName);//查询话题信息
        if (!isset($topicInfo['topic_id'])) {
            return 0;
        }
        $arrIds = $this->getAllPostIdFromTopic($topicInfo['topic_id']);//查询话题的全部帖子ID
        if (!$arrIds) {
             return 0;
        }
        $strIds = implode(',',$arrIds);
        return $this->db->getOne("select count(1) as cnt from r_news where news_id in($strIds)");//查询帖子的用户数
    }
}